package com.ggqq.controller.admin;

import com.ggqq.entity.User;
import com.ggqq.service.UserService;
import com.ggqq.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Date;

/**
 * 用户登录 控制器
 * */
@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private UserService userService;

    /** 跳转登录页面*/
    @GetMapping
    public String loginPage(){
        return "admin/login";
    }

    /**
     * 登录校验
     * username:用户名
     * password:密码
     * session:session域
     * attributes:返回页面消息
     * 登录成功跳转登录成功页面，登录失败返回登录页面
     */
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes){
        User user = userService.checkUser(username, password);
        if(user != null){
            user.setPassword(null);
            session.setAttribute("user",user);

            return "admin/index";//返回管理的首页
        }else{
            attributes.addFlashAttribute("message","请仔细核对您的用户名或者密码是否正确，如您是新用户，请先注册后再登录！");
            return "redirect:/admin";//重定向到登录页
        }
    }

    //返回注册页面
    @RequestMapping("/toRegister")
    public String input(){
        return "admin/register";
    }

    //注册界面
    @RequestMapping("/registerSuccess")
    public String register(@Valid User user,RedirectAttributes attributes){
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setType(1);
        user.setPassword(MD5Utils.code(user.getPassword()));//对密码加密后存入数据库
        int add = userService.insertByUsernameAndPassword(user);
        if(add == 0){
            attributes.addFlashAttribute("message","注册失败，请仔细核对内容！");
        }else {
            attributes.addFlashAttribute("message","注册成功,请登录！");
        }
        return "redirect:/admin";//重定向到登录页
    }

    /**
     * 注销
     * session:session域
     * 返回登录页面
     */
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/admin";
    }
}
